const AppId = "meAkfsx1yj9YkMLEBw7L37";
const Appkey = "ixmykyJN9z7wtRX1ifusv";
const Mastersecret = "5QSuEcX9P37UI39pKr9S75";

const BaseUrl = `https://restapi.getui.com/v2/${AppId}`;

const crypto = require("crypto");
const {
	InsideErr,
	BaseErr
} = require("utils");
const db = uniCloud.database();
const {
	nanoid
} = require('nanoid');


// 请求
async function request(path, options) {
	try {
		let url = `${BaseUrl}${path}`;
		let re = await uniCloud.httpclient.request(url, options);
		// 解析下 re
		let {
			code,
			msg,
			data
		} = re.data || {};
		// 这就错误咯
		if (code !== 0) {
			return [new BaseErr(code, msg), null];
		}
		return [null, data];
	} catch (e) {
		return [new InsideErr(e), null];
	}
}

async function getData(path, data, headers = {}) {
	return await request(path, {
		data: data,
		contentType: "json",
		dataType: "json",
		headers: headers
	})
}


async function postData(path, data, headers = {}) {
	return await request(path, {
		method: "POST",
		dataAsQueryString: false,
		data: data,
		contentType: "json",
		dataType: "json",
		headers: headers
	});
}
// 个推签名
function gtSign(t) {
	// 示例 java 代码格式: String sign = sha256(appkey+timestamp+mastersecret)
	const hash = crypto.createHash('sha256');
	hash.update(`${Appkey}${t}${Mastersecret}`);
	return hash.digest('hex');
}

// 注册token
async function registerToken() {
	let t = Date.now();
	let sign = gtSign(t);
	let [err, res] = await postData("/auth", {
		sign: sign,
		timestamp: t,
		appkey: Appkey
	})
	if (err) {
		return null;
	}
	let {
		token,
		expire_time
	} = res;
	let expire = Number(expire_time);
	let collection = db.collection("gtToken");
	await collection.add({
		token: token,
		expire: expire
	});
	return token;
}


// 获取个推token
async function gtToken() {
	// 要还要6个小时 才过期的
	let dateNow = Date.now() + 6 * 3600 * 1000;
	// 获取
	let tokeCollection = db.collection("gtToken");
	let tokenArr = await tokeCollection.where({
		expire: db.command.gt(dateNow)
	}).get();
	// 删除 过期的
	await tokeCollection.where({
		expire: db.command.lt(dateNow)
	}).remove();
	// 如果小于3个, 就 新增吧
	if (tokenArr.data.length <= 2) {
		// 新增一个token
		let newToken = await registerToken();
		if (!newToken && tokenArr.data.length > 0) {
			return tokenArr.data[0].token;
		}
		return newToken;
	} else {
		return tokenArr.data[0].token;
	}
}

// 创建 消息
async function createPushMessage(token, {
	title = "",
	content = "",
	payload = ""
} = {}) {
	// 透传消息
	let transmission = {
		title,
		content,
		payload
	};
	let transmissionDes = JSON.stringify(transmission);
	console.log("透传消息", transmissionDes);
	
	let data = {
		"request_id": nanoid(),
		"settings": {
			"ttl": 3 * 24 * 3600 * 1000
		},
		"push_message": {
			"transmission": transmissionDes
		},
		"push_channel": {
			"ios": {
				"type": "notify",
				"auto_badge": "+1",
				"aps": {
					"alert": {
						"title": title,
						"body": content
					},
					"content-available": 0,
					"sound": "default"
				},
				"payload": transmissionDes
			}
		}
	};
	return await postData("/push/list/message", data, {
		token: token
	});
}


// 去推送
async function gtPush(cidArr, message) {
	if (!Array.isArray(cidArr)) {
		return;
	}
	if (cidArr.length === 0) {
		return;
	}

	// 获取token
	let token = await gtToken();
	if (!token) {
		return;
	}
	// 创建推送消息
	let [taskErr, taskRes] = await createPushMessage(token, message);
	if (taskErr) {
		return;
	}
	
	// 去推送
	let pushData = {
		"audience": {
			"cid": cidArr
		},
		"taskid": taskRes.taskid, // 消息id
		"is_async": true
	}
	await postData("/push/list/cid", pushData, {
		token: token
	})
}



module.exports = {
	gtPush: gtPush
}
